package doh.login;
import doh.entity.Player;
import doh.service.ValidatorService;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;

public class LoginService {

    @PersistenceContext
    private EntityManager em;
    private CriteriaBuilder cb;
    private static ArrayList<String> usersOnline;

    public static void addOnlineUser(String id){
        if(usersOnline == null){
            usersOnline = new ArrayList<String>();
        }
        usersOnline.add(id);
    }

    public static boolean isUserOnline(String id){
        if(usersOnline == null){
            return false;
        } else {
            for(int i=0; i<usersOnline.size(); i++){
                if(usersOnline.get(i).equals(id)){
                    return true;
                }
            }
        }
        return false;

    }

    public static void removeOnlineUser(String id){
        if(usersOnline == null) return;
        for(int i=0; i<usersOnline.size(); i++){
            if(usersOnline.get(i).equals(id)){
                usersOnline.remove(i);
                return;
            }
        }
    }

    /**
     * returns a deep copy of the arraylist
     * @return
     */
    public static ArrayList<String> getOnlineUsers(){
        if(usersOnline == null) return null;
        ArrayList<String> newList = new ArrayList<String>();
        for(int i=0; i<usersOnline.size(); i++){
            newList.add(usersOnline.get(i));
        }
        return newList;
    }


    public LoginService(EntityManager em, CriteriaBuilder cb){
        this.em = em;
        this.cb = cb;
    }
//    @PostConstruct
//    private void init() {
//        cb = em.getCriteriaBuilder();
//    }

//    public boolean loginAs(String user, String password){
//        return this.login(user, password);
//    }

    public boolean login(String id, String password){
        if(ValidatorService.isValidInput(id) && ValidatorService.isValidInput(password)){
            String hpasswd = getMD5(password);
            Player p = em.find(Player.class, id);
            if(p != null && p.get_password().equals(hpasswd) && !isUserOnline(id)){
                addOnlineUser(id);
                return true;
            }
        }
        return false;
    }

    static String getMD5(String password){
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            byte[] data = password.getBytes();
            m.update(data, 0, data.length);
            BigInteger i = new BigInteger(1, m.digest());
            return String.format("%1$032X", i);
        } catch (NoSuchAlgorithmException e){
            e.printStackTrace();
            return null;
        }
    }

//    @PreDestroy
//    private void tearDown(){
//        em.close();
//    }
}
